'use strict';

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ErrorOverlayPlugin = require('error-overlay-webpack-plugin');
const utils = require('../utils');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const LoadablePlugin = require('@loadable/webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
/**
 *
 * @param {object} data
 * @param {*} data.buildPath
 * @param {*} data.mainPath
 * @param {*} data.moduleName
 * @param {*} data.gitLoacl
 * @param {*} data.ctx
 */
module.exports = function (data, config) {
  return {
    entry: {
      main: utils.resolve('template/_app.tsx'),
    },
    output: {
      path: path.join(data.buildPath, 'prod'),
      filename: 'js/[name].[hash:8].js',
      chunkFilename: 'js/[name].[hash:8].chunk.js',
    },
    optimization: {
      minimize: true,
      minimizer: [new TerserPlugin({
        exclude: /\/excludes/,
      }), new OptimizeCssPlugin()],
    },
    mode: 'production',
    stats: { children: false, warnings: false },
    resolve: utils.getResolve(data, config),
    resolveLoader: utils.getResolveLoader(data),
    externals: {
      vue: 'Vue',
    },
    // optimization: {
    //   splitChunks: {
    //     chunks: 'all',
    //     name: 'common',
    //   },
    // },
    module: {
      noParse: /^(vue|vue-router|vuex|vuex-router-sync)$/,
      rules: [
        utils.getVueLoader(),
        utils.getImageLoader(),
        utils.getLessLoader(false, config),
        utils.getCssLoader(false, config),
        utils.getMediaLoader(),
        utils.getFontsLoader(),
        utils.getSvgLoader(),
        ...utils.getTsLoader(data, config),
      ],
    },
    plugins: [
      new CleanWebpackPlugin(),
      new VueLoaderPlugin(),
      new ErrorOverlayPlugin(),
      new LoadablePlugin({
        filename: 'loadable-stats.prod.json',
        writeToDisk: {
          filename: data.buildPath,
        },
      }),
      new MiniCssExtractPlugin({
        filename: 'style/[name].[hash:8].css',
      }),
      // new PreloadWebpackPlugin({
      //   rel: 'preload',
      //   include: 'initial',
      // }),
      new HtmlWebpackPlugin({
        template: utils.resolve('views/dev-index.html'),
        filename: 'index.html',
        inject: 'body',
        title: 'aaaaa',
      }),

      new webpack.LoaderOptionsPlugin({
        debug: true,
        minimize: false,
        options: {
          context: data.mainPath,
        },
      }),
    ],
  };
};
